package me.zhengjie.business.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.base.OrgWeightVo;
import me.zhengjie.business.domain.*;
import me.zhengjie.business.domain.sup.Gsgl;
import me.zhengjie.business.repository.*;
import me.zhengjie.business.service.Kc04Service;
import me.zhengjie.business.service.ZhsqGlService;
import me.zhengjie.business.service.ZhsqHistoryService;
import me.zhengjie.business.service.dto.ZhsqDto;
import me.zhengjie.business.service.mapstruct.ZhsqMapper;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.repository.LocalStorageRepository;
import me.zhengjie.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description 服务实现
 * @author xiahongbo
 * @date 2024-02-18
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ZhsqGlServiceImpl implements ZhsqGlService {

    private final FpryRepository fpryRepository;
    private final ZhsqRepository zhsqRepository;
    private final HljgRepository hljgRepository;
    private final GsglRepository gsglRepository;
    private final LocalStorageRepository localStorageRepository;
    private final AdlZhsqRepository adlZhsqRepository;
    private final ZhsqHistoryService zhsqHistoryService;
    private final Kc04Service kc04Service;

    private final UserService userService;

    private final ZhsqMapper zhsqMapper;

    @PersistenceContext
    private EntityManager em;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhsqDto createGl(Zhsq resources, String ids, String delay) {
        log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 start");
        log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 - 新增照护图片：{} ", ids);
        Gsgl gsgl = gsglRepository.queryGsgl(SecurityUtils.getCurrentUserId());
        Hljg hljg = hljgRepository.findById(gsgl.getBisGsglId()).orElseGet(Hljg::new);
        //resources.setBisZhsqId(IdUtil.simpleUUID());
        resources.setHljg(hljg);
        resources.setBisZhsqHljgBm(hljg.getBisGsglYljgdm());

        String pggsId = hljg.getPggs() == null ? "" : hljg.getPggs().getBisGsglId();
        String sbgsId = hljg.getSbgs() == null ? "" : hljg.getSbgs().getBisGsglId();
        String pggsName = hljg.getPggs() == null ? "" : hljg.getPggs().getBisGsglQymc();
        String sbgsName = hljg.getSbgs() == null ? "" : hljg.getSbgs().getBisGsglQymc();

        // 判断护理机构是否存在评估公司
        if(StringUtils.isEmpty(pggsId) && StringUtils.isEmpty(sbgsId)) {



        } else if(StringUtils.isEmpty(pggsId)) {
            log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 - 评估公司为空，商保公司代为评估：{} ", sbgsName);
            resources.setBisSbgsId(sbgsId);
            resources.setBisPggsId(sbgsId);
        } else {
            log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 - 评估公司不为空，商保公司复核：{}，评估公司评估：{} ", sbgsName, pggsName);
            resources.setBisSbgsId(sbgsId);
            resources.setBisPggsId(pggsId);
        }

        String sndj = resources.getBisZhsqSndj();

        log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 - 失能等级 - {}", sndj);
        resources.setBisZhsqSndj(sndj);
        Date dykkrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateTimeUtil.getNow(), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);

        Date dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(new Date()), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
        log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 - 85周岁以上，待遇期为年末最后一天");
        log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 - 待遇开始日期：{}，待遇结束日期：{} ", dykkrq, dyjsrq);
        int months = DateTimeUtil.diffMonths(dyjsrq, dykkrq);
        months = months == 0 ? 1 : months;
        resources.setBisZhsqDykkrq(dykkrq);
        resources.setBisZhsqDyjsrq(dyjsrq);
        resources.setBisZhsqXsdyq(months+"个月");

        log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 - 照护类别：入住机构护理[01] ");
        resources.setBisZhsqZhlb("01");

        //resources.setBisZhsqAdlPc("402883ba943fefb7019444d38ee10002");

        // 如果是延期申请，先要终止当前待遇
        if("1".equals(delay)) {
            String yestday = DateTimeUtil.getDateTime(DateTimeUtil.addDays(dykkrq, -1), DateTimeUtil.DEFAULT_DATE_FORMAT);
            kc04Service.stopZhsq(resources.getBisZhsqSnrySfz(), yestday, 0l, "延期终止");
        }

        // 新增adl量表
        resources.setBisZhsqId(null);
        Zhsq newZhsq = zhsqRepository.save(resources);

        // 新增照片
        if("1".equals(delay)) {
            if(ids != null && !ids.equals("")){
                log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构延期照护申请 - 关联附件 ");
                String[] picIds = ids.split(",");
                for (String picId:picIds) {
                    Long storage_id = Long.parseLong(picId);
                    LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                    if(StringUtils.isEmpty(localStorage.getYwid())) {
                        localStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                        localStorageRepository.save(localStorage);
                    } else {
                        LocalStorage newlocalStorage = new LocalStorage();
                        newlocalStorage.setRealName(localStorage.getRealName());
                        newlocalStorage.setName(localStorage.getName());
                        newlocalStorage.setSuffix(localStorage.getSuffix());
                        newlocalStorage.setPath(localStorage.getPath());
                        newlocalStorage.setType(localStorage.getType());
                        newlocalStorage.setSize(localStorage.getSize());
                        newlocalStorage.setFjlb(localStorage.getFjlb());
                        newlocalStorage.setPath2(localStorage.getPath2());
                        newlocalStorage.setPath3(localStorage.getPath3());
                        newlocalStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                        localStorageRepository.save(newlocalStorage);
                    }
                }
            }
        } else {
            if(ids != null && !ids.equals("")){
                log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 - 关联附件 ");
                String[] picIds = ids.split(",");
                for (String picId:picIds) {
                    Long storage_id = Long.parseLong(picId);
                    LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                    localStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                    localStorageRepository.save(localStorage);
                }
            }
        }

        log.info("[ZhsqGlServiceImpl - createGl]--------------- 机构新增照护申请 end");

        return zhsqMapper.toDto(newZhsq);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhsqDto submitGl(Zhsq resources, String ids, String delay) {
        log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 start");
        Gsgl gsgl = gsglRepository.queryGsgl(SecurityUtils.getCurrentUserId());
        // 如果是延期申请，清空主键
        if("1".equals(delay)) {
            resources.setBisZhsqId(null);
        }
        if(StringUtils.isEmpty(resources.getBisZhsqId())) {  // 没有主键ID，表示新增
            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 - 没有主键ID，表示新增");
            Hljg hljg = hljgRepository.findById(gsgl.getBisGsglId()).orElseGet(Hljg::new);
            //resources.setBisZhsqId(IdUtil.simpleUUID());
            resources.setHljg(hljg);
            resources.setBisZhsqHljgBm(hljg.getBisGsglYljgdm());

            String sndj = resources.getBisZhsqSndj();
            resources.setBisZhsqSndj(sndj);
            Date dykkrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateTimeUtil.getNow(), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
            //Date tempDate = DateTimeUtil.addMonths(dykkrq, Integer.parseInt(dyqx));
            //Date dyjsrq = DateTimeUtil.addDays(tempDate, -1);

            Date dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(new Date()), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构新增照护申请 - 85周岁以上，待遇期为年末最后一天");
            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构新增照护申请 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
            int months = DateTimeUtil.diffMonths(dyjsrq, dykkrq);
            months = months == 0 ? 1 : months;
            resources.setBisZhsqDykkrq(dykkrq);
            resources.setBisZhsqDyjsrq(dyjsrq);
            resources.setBisZhsqXsdyq(months+"个月");

            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 - 失能等级 - {}", sndj);
            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 - 待遇期限 - {}", months + "个月");


            int age = Integer.parseInt(resources.getBisZhsqNl());
            resources.setBisZhsqNl(String.valueOf(age));
            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 - 计算年龄 {} ", age);

            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 - 照护类别：入住机构护理[01] ");
            resources.setBisZhsqZhlb("01");

            //resources.setBisZhsqAdlPc("402883ba943fefb7019444d38ee10002");

            resources.setBisZhsqTjsj(new Date());
            Zhsq tempZhsq = zhsqRepository.queryGlSqlb(resources.getBisZhsqSnrySfz(), DateTimeUtil.getDateTime(resources.getBisZhsqTjsj(), DateTimeUtil.DEFAULT_DATE_FORMAT));
            if(tempZhsq == null) {
                resources.setBisZhsqSqlb("10");
            } else {
                resources.setBisZhsqSqlb("20");
            }
            log.info("resources:---------------------- {}",resources);


            // 如果是延期申请，先要终止当前待遇
            if("1".equals(delay)) {
                resources.setBisZhsqSqlb("20");
                String yestday = DateTimeUtil.getDateTime(DateTimeUtil.addDays(dykkrq, -1), DateTimeUtil.DEFAULT_DATE_FORMAT);
                kc04Service.stopZhsq(resources.getBisZhsqSnrySfz(), yestday, 0l, "延期终止");
            }

            // 新增adl量表
            Zhsq newZhsq = zhsqRepository.save(resources);

            // 新增照片
            if("1".equals(delay)) {
                if(ids != null && !ids.equals("")){
                    log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构延期照护申请 - 关联附件 ");
                    String[] picIds = ids.split(",");
                    for (String picId:picIds) {
                        Long storage_id = Long.parseLong(picId);
                        LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                        if(StringUtils.isEmpty(localStorage.getYwid())) {
                            localStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                            localStorageRepository.save(localStorage);
                        } else {
                            LocalStorage newlocalStorage = new LocalStorage();
                            newlocalStorage.setRealName(localStorage.getRealName());
                            newlocalStorage.setName(localStorage.getName());
                            newlocalStorage.setSuffix(localStorage.getSuffix());
                            newlocalStorage.setPath(localStorage.getPath());
                            newlocalStorage.setType(localStorage.getType());
                            newlocalStorage.setSize(localStorage.getSize());
                            newlocalStorage.setFjlb(localStorage.getFjlb());
                            newlocalStorage.setPath2(localStorage.getPath2());
                            newlocalStorage.setPath3(localStorage.getPath3());
                            newlocalStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                            localStorageRepository.save(newlocalStorage);
                        }
                    }
                }
            } else {
                if(ids != null && !ids.equals("")){
                    log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 - 关联附件 ");
                    String[] picIds = ids.split(",");
                    for (String picId:picIds) {
                        Long storage_id = Long.parseLong(picId);
                        LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                        localStorage.setYwid(String.valueOf(resources.getBisZhsqId()));
                        localStorageRepository.save(localStorage);
                    }
                }
            }
            //
            if("'220102','220103','220104','220105','220106','220107','220108','220109','220110', '220176', '220199'".indexOf(gsgl.getBisGsglSsqx())!=-1) {
                List<OrgWeightVo> listWeight = userService.queryUserWeight(220101l, "54");
                int prizeIndex = WeightUtil.getOrgWeigth(listWeight);
                OrgWeightVo prizeDto = listWeight.get(prizeIndex);
                Long userId = prizeDto.getId();
                String userName = prizeDto.getName();
                log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 - 随机分配 - 初审人员ID {}，初审人员姓名 {} ", userId, userName);

                Fpry fpry = new Fpry();
                fpry.setBisFpryId(IdUtil.simpleUUID());
                fpry.setBisFpryZhsqId(newZhsq.getBisZhsqId());
                fpry.setBisFpryRyglId(userId);
                fpry.setBisFpryRyglXm(userName);
                fpry.setBisFpryFpsj(new Date());
                fpry.setBisFpryZt("0");
                fpryRepository.save(fpry);
            }


            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 end");
            return zhsqMapper.toDto(newZhsq);
        } else {  // 存在主键ID，表示修改
            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 - 存在主键ID，表示修改");


            ZhsqHistory zhsqHistory = zhsqHistoryService.queryBh11(resources.getBisZhsqId());

            if(zhsqHistory == null) {

                Date currentDate = DateTimeUtil.parse(DateTimeUtil.getDate() + " 23:59:59", DateTimeUtil.DEFAULT_DATETIME_FORMAT);
                Date saveDate = resources.getLrsj();
                long diff = DateTimeUtil.diffDays(currentDate, saveDate);
                log.info("当前日期 {} ", DateTimeUtil.getDateTime(currentDate, DateTimeUtil.DEFAULT_DATE_FORMAT));
                log.info("保存日期 {} ", DateTimeUtil.getDateTime(saveDate, DateTimeUtil.DEFAULT_DATE_FORMAT));
                log.info("相差天数 {} ", diff);
                if(diff >= 4) {
                    resources.setBisZhsqTjsj(new Date());
                } else {
                    resources.setBisZhsqTjsj(saveDate);
                }
            }

            Zhsq tempZhsq = zhsqRepository.queryGlSqlb(resources.getBisZhsqSnrySfz(), DateTimeUtil.getDateTime(resources.getBisZhsqTjsj(), DateTimeUtil.DEFAULT_DATE_FORMAT));
            if(tempZhsq == null) {
                resources.setBisZhsqSqlb("10");
            } else {
                resources.setBisZhsqSqlb("20");
            }

            ZhsqDto zhsqDto = this.updateGl(resources, ids);

            if("'220102','220103','220104','220105','220106','220107','220108','220109','220110', '220176', '220199'".indexOf(gsgl.getBisGsglSsqx())!=-1) {
                List<OrgWeightVo> listWeight = userService.queryUserWeight(220101l, "54");
                int prizeIndex = WeightUtil.getOrgWeigth(listWeight);
                OrgWeightVo prizeDto = listWeight.get(prizeIndex);
                Long userId = prizeDto.getId();
                String userName = prizeDto.getName();
                log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 - 随机分配 - 初审人员ID {}，初审人员姓名 {} ", userId, userName);

                Fpry fpry = new Fpry();
                fpry.setBisFpryId(IdUtil.simpleUUID());
                fpry.setBisFpryZhsqId(zhsqDto.getBisZhsqId());
                fpry.setBisFpryRyglId(userId);
                fpry.setBisFpryRyglXm(userName);
                fpry.setBisFpryFpsj(new Date());
                fpry.setBisFpryZt("0");
                fpryRepository.save(fpry);
            }

            log.info("[ZhsqGlServiceImpl - submitGl]--------------- 机构提交照护申请 end");
            return zhsqDto;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhsqDto updateGl(Zhsq resources, String ids) {
        log.info("[ZhsqGlServiceImpl - updateGl]--------------- 机构修改照护申请 start");

        Zhsq zhsq = zhsqRepository.findById(resources.getBisZhsqId()).orElseGet(Zhsq::new);
        ValidationUtil.isNull( zhsq.getBisZhsqId(),"Zhsq","id",resources.getBisZhsqId());
        zhsq.copy(resources);
        Date lrsj = zhsq.getBisZhsqTjsj() == null ? zhsq.getLrsj() : zhsq.getBisZhsqTjsj();

        String sndj = resources.getBisZhsqSndj();
        zhsq.setBisZhsqSndj(sndj);
        Date dykkrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(lrsj, DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
        Date dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(new Date()), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
        log.info("[ZhsqGlServiceImpl - updateGl]--------------- 机构修改照护申请 - 85周岁以上，待遇期为年末最后一天");
        log.info("[ZhsqGlServiceImpl - updateGl]--------------- 机构修改照护申请 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
        int months = DateTimeUtil.diffMonths(dyjsrq, dykkrq);
        months = months == 0 ? 1 : months;
        zhsq.setBisZhsqDykkrq(dykkrq);
        zhsq.setBisZhsqDyjsrq(dyjsrq);
        zhsq.setBisZhsqXsdyq(months+"个月");

        log.info("[ZhsqGlServiceImpl - updateGl]--------------- 机构修改照护申请 - 失能等级 - {}", sndj);
        log.info("[ZhsqGlServiceImpl - updateGl]--------------- 机构修改照护申请 - 待遇期限 - {}", months + "个月");

        // 新增照片
        if(ids != null && !ids.equals("")){
            log.info("[ZhsqGlServiceImpl - updateGl]--------------- 机构修改照护申请机构修改照护申请 - 关联附件 ");

            String[] picIds = ids.split(",");
            for (String picId:picIds) {

                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(resources.getBisZhsqId()));
                localStorageRepository.save(localStorage);
            }
        }

        log.info("[ZhsqGlServiceImpl - updateGl]--------------- 机构修改照护申请 end");
        return zhsqMapper.toDto(zhsqRepository.save(zhsq));
    }

}
